/*
#Copyright (c) 2013, Philippe Bordron <philippe.bordron@gmail.com>
#
# This file is part of SIPPER.
#
# DCC is free software: you can redistribute it and/or modify
# it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DCC is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU LESSER GENERAL PUBLIC LICENSE for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# along with SIPPER.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * 
 * @author Philippe Bordron
 *
 */

package combi.sipper.io;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import combi.utils.Couple;

public class IOQueriesFile {

	private String fileName;
	private static String SEPARATOR = " ";

	public IOQueriesFile(String fileName)
	{
		setFile(fileName);
	}

	public List<Couple<List<String>, List<String>>> read() throws IOException
	{
		List<Couple<List<String>, List<String>>> result = new ArrayList<Couple<List<String>, List<String>>>();
		BufferedReader in = new BufferedReader(new FileReader(fileName));	
		String ch;
		while ((ch = in.readLine()) != null)
		{
			//System.err.println(ch);
			//get the source set and the destination set
			String[] parts = ch.split("\\s+");
			Pattern p = Pattern.compile("([^\\s]+)");
			Matcher m = p.matcher(parts[0]);
			List<String> src = new ArrayList<String>();
			while (m.find())
			{
				src.add(m.group(1));
			}
			m = p.matcher(parts[1]);
			List<String> dest = new ArrayList<String>();
			while (m.find())
			{
				dest.add(m.group(1));
			}
			result.add(new Couple<List<String>, List<String>>(src, dest));
		}

		in.close();
		return result;
	}

	public void write(List<Couple<List<String>, List<String>>> list) throws IOException
	{
		BufferedWriter out = new BufferedWriter(new FileWriter(fileName));	
		for (Couple<List<String>, List<String>> elem : list)
		{
			out.write(elem.getFirst().toString().replaceAll("[,\\[\\]]", "") + SEPARATOR + elem.getSecond().toString().replaceAll("[,\\[\\]]", "")+"\n");
		}
		out.close();
	}

	public void setFile(String fileName)
	{
		this.fileName = fileName;
	}

	public String getFileName()
	{
		return this.fileName;
	}


}
